package com.huluobo.jetpackdemo.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.Flow

/**
 *  Created by LC on 2024/10/17.
 */
class PagingViewModel : ViewModel() {
    //  cachedIn(viewModelScope) 加不加都行,加上这句话表示当前的flow流可以缓存到viewModel的协程作用域
    fun getPagingData(): Flow<PagingData<Item>> {
        return Repo.getPagingData().cachedIn(viewModelScope)
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val apiService = ApiService.create()

    //PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5)
    //prefetchDistance 表示神域多少数据的时候开始预加载
    //如果设置为0表示滑动到底部才进行加载,默认值是当前分页的大小,也就是剩余5条的时候开始进行预加载
    //当前预加载的大小是size的5倍,也就是剩余不足25条的时候进行预加载
    //flow让数据形成一个flow流,可以给页面进行发送
    //pagingSourceFactory 数据加载工厂,直接放之前写的数据源的类即可

    fun getPagingData(): Flow<PagingData<Item>> {
        return Pager(
            pagingSourceFactory = { RepoPagingSource(apiService) },
            config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5)
        ).flow
    }
}